package per.mnxc.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import per.mnxc.common.EmailUtil;
import per.mnxc.common.R;
import per.mnxc.common.ValidateCodeUtils;
import per.mnxc.dto.AdminDto;
import per.mnxc.pojo.Admin;
import per.mnxc.service.IAdminService;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mnxc
 * @since 2022-11-26
 */
@Api(tags = "管理员相关接口")
@RestController
@RequestMapping("/admin")
@CrossOrigin(origins = "*",maxAge = 3600)
public class AdminController {

    @Value("${admin.secretKey}")
    String adminKey;

    @Autowired
    IAdminService adminService;

    /**
     * @description: 批量逻辑删除
     * @author: mnxc
     * @date: 2022/11/27 13:51
     * @param: [ids]
     * @return: per.mnxc.common.R<java.lang.String>
     **/
    @ApiOperation("批量逻辑删除接口")
    @ApiImplicitParam(name = "ids",value = "传入id example: /1,2,3")
    @DeleteMapping("/{ids}")
    public R<String> removeByIds(@PathVariable List<Long> ids){

        adminService.removeByIds(ids);
        return R.success("删除成功");
    }

    /**
     * @description: 添加管理员
     * @author: mnxc
     * @date: 2022/11/27 13:31
     * @param: [admin]
     * @return: per.mnxc.common.R<java.lang.String>
     **/
    @ApiOperation("添加管理员接口")
    @ApiImplicitParam(name = "admin",value = "管理员初始密码为 123456 ,必要属性 电话号码，姓名")
    @PostMapping
    public R<String> save(@RequestBody Admin admin){
        if(admin==null)
            return R.error("添加管理员失败");
        String password = DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8));
        admin.setAdminPWD(password);
        adminService.save(admin);
        return R.success("添加管理员成功");
    }

    /**
     * @description: 管理员信息修改
     * @author: mnxc
     * @date: 2022/11/27 13:29
     * @param: [admin]
     * @return: per.mnxc.common.R<java.lang.String>
     **/
    @ApiOperation("管理员信息修改接口")
    @ApiImplicitParam(name="admin",value = "必要属性：id",required = true)
    @PutMapping
    public R<String> update(@RequestBody Admin admin){
        if(admin==null)
            return R.error("修改信息失败");
        //密码md5加密
        if(admin.getAdminPWD()!=null) {
            String pwd = DigestUtils.md5DigestAsHex(admin.getAdminPWD().getBytes(StandardCharsets.UTF_8));
            admin.setAdminPWD(pwd);
        }
        adminService.updateById(admin);
        return R.success("修改信息成功");
    }

    /**
     * @description: 管理员登录
     * @author: mnxc
     * @date: 2022/11/27 2:27
     * @param: [admin]
     * @return: per.mnxc.common.R<per.mnxc.pojo.Admin>
     **/
    @ApiOperation("管理员登录接口")
    @ApiImplicitParam(name = "admin",value = "必填属性：管理员电话和密码",required = true,paramType = "query")
    @PostMapping("/login")
    public R<Admin> login(HttpServletRequest request, @RequestBody Admin admin){
        //1.密码md5加密
        String password = admin.getAdminPWD();
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8));
        //2.根据电话号码查管理员数据
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getAdminPhone,admin.getAdminPhone());
        Admin one = adminService.getOne(lambdaQueryWrapper);
        if(one==null){
            //则无此管理员
            return R.error("登陆失败");
        }else if(!one.getAdminPWD().equals(pwd)){
            //密码错误
            return R.error("登陆失败");
        }
        //登录成功,记录登录的管理员信息
        request.getSession().setAttribute("adminId",one.getAdminId());
        //抹除重要信息
        one.setAdminPWD("");
        return R.success(one);
    }

    @ApiOperation("管理员退出登陆接口")
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理管理员登录信息
        request.getSession().removeAttribute("adminId");
        return R.success("退出登录成功");
    }
    /**
     * @description: 管理员信息分页查询
     * @author: mnxc
     * @date: 2022/11/27 1:19
     * @param: [page , pageSize, name]
     * @return: com.baomidou.mybatisplus.core.metadata.IPage<per.mnxc.pojo.Admin>
     **/
    @ApiOperation("管理员分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page",value = "当前页码，从1开始",paramType = "query",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页显示记录数，从1开始",paramType = "query",required = true),
            @ApiImplicitParam(name = "name",value = "查询条件-管理员姓名",paramType = "query")
    })
    @GetMapping("/page")
    public R<IPage<Admin>> page(int page, int pageSize, String name){
        //1.构造分页器
        System.out.println("admin/page请求了一次");
        IPage<Admin> pageInfo = new Page<>(page,pageSize);
        //2.构造条件查询器
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(name!=null,Admin::getAdminName,name);
        //3.查询结果
        adminService.page(pageInfo,lambdaQueryWrapper);
        //4.清除重要数据，再返回结果(例如密码)
        List<Admin> admins = pageInfo.getRecords();
        admins.forEach((item)->{
            item.setAdminPWD("");
        });
        pageInfo.setRecords(admins);
        return R.success(pageInfo);
    }

    @ApiOperation("获取管理员注册验证码接口")
    @ApiImplicitParam(name = "admin",value = "必填属性：邮箱地址")
    @PostMapping("/sendMessage")
    public R<String> sendMsg(HttpServletRequest request,@RequestBody Admin admin){
        //1.调用邮箱验证码推送
        Integer code = ValidateCodeUtils.generateValidateCode(6);
        String addr = admin.getAdminEmail();
        EmailUtil.sendEmail("管理员注册验证","[MNXC]",addr,code);
        //2.记录验证码
        request.getSession().setAttribute(addr,code);
        return R.success("验证码发送成功");
    }
    @ApiOperation("管理员注册接口")
    @ApiImplicitParam(name = "adminDto",value = "需要先申请验证码,才能注册")
    @PostMapping("/register")
    public R<String> register(HttpServletRequest request,@RequestBody AdminDto adminDto){
        //1.验证-->验证码
        String addr = adminDto.getAdminEmail();
        String code = String.valueOf(request.getSession().getAttribute(addr));
        if(code == null)return R.error("注册失败");
        if(!code.equals(adminDto.getCode())){
            return R.error("注册失败，验证码错误");
        }
        //2.验证-->管理员注册密匙
        if(!adminKey.equals(adminDto.getSecretKey())){
            return R.error("注册失败");
        }
        //3.验证-->管理员电话是否已注册
        LambdaQueryWrapper<Admin> lqw = new LambdaQueryWrapper<>();
        lqw.eq(adminDto.getAdminPhone()!=null,Admin::getAdminPhone,adminDto.getAdminPhone());
        Admin one = adminService.getOne(lqw);
        if(one !=null)return R.error("电话号码已被注册！");
        //4.添加管理员
        //4.1密码md5加密
        String adminPWD = adminDto.getAdminPWD();
        adminPWD = DigestUtils.md5DigestAsHex(adminPWD.getBytes(StandardCharsets.UTF_8));
        adminDto.setAdminPWD(adminPWD);
        adminService.save(adminDto);
        return R.success("管理员注册成功");
    }
}

